from . import api
from ihome.utils.commons import login_required
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.models import User, UserAddress, HouseCollection, House, Order
from ihome.utils.image_storage import storage
from ihome import db, constants
import os

# get_house_order()
# pay_house_order()
# cancel_house_order()
# evaluate_house_order()


@api.route("/order/get_house_order", methods=["GET"])
@login_required
def get_order():
    """获取订单信息
        用户下的订单
    """
    # 　查询当前用户发布的房屋
    user_id = g.user_id
    order_status = request.args.get("status")

    filter_params = []
    if order_status == "await_pay":
        filter_params.append(Order.status == 'WAIT_PAYMENT')
    # 价格区间
    elif order_status == "wait_comment":
        filter_params.append(Order.status == 'WAIT_COMMENT')
    # 房屋类型
    elif order_status == "complete":
        filter_params.append(Order.status == 'COMPLETE')

    # 查询订单数据
    try:
        # 查询登录用户的订单
        orders = Order.query.filter_by(user_id=user_id).filter(*filter_params).order_by(Order.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    orders_dict_list = []
    for order in orders:
        orders_dict_list.append(order.to_dict())

    return jsonify(errno=RET.OK, errmsg="查询成功", data=orders_dict_list)


@api.route("/order/cancel_order", methods=["GET"])
@login_required
def cancel_order():
    """获取订单信息
        用户下的订单
        :param:order_id
    """
    # 　查询当前用户发布的房屋
    # user_id = g.user_id
    order_id = request.args.get("order_id")

    # 保存取消状态到数据库
    try:
        Order.query.filter_by(id=order_id).update(
            {"status": "CANCELED"})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据出现错误")

    return jsonify(errno=RET.OK, errmsg="取消成功")


@api.route("/order/get_pay_order", methods=["GET"])
@login_required
def get_pay_order():
    """获取支付的订单信息
        :param:order_id
    """
    # 　查询当前用户发布的房屋
    user_id = g.user_id
    order_id = request.args.get("order_id")

    try:
        order = Order.query.filter_by(id=order_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据出现错误")
    if order is None:
        return jsonify(errno=RET.NODATA,errmsg="订单信息不存在")

    return jsonify(errno=RET.OK, errmsg="OK", data=order.to_dict())


@api.route("/order/comment_order", methods=["POST"])
@login_required
def comment_order():
    """评论订单
        :param:order_id
    """
    # 　查询当前用户发布的房屋
    # user_id = g.user_id
    order_id = request.get_json().get("order_id")
    comment = request.get_json().get("comment")

    try:
        Order.query.filter_by(id=order_id).update({"status": "COMPLETE", "comment": comment})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

    return jsonify(errno=RET.OK, errmsg="OK")
